package com.xgk.boot.module.core.controller.admin.truck;

import com.xgk.boot.framework.common.pojo.CommonResult;
import com.xgk.boot.framework.common.pojo.PageResult;
import com.xgk.boot.module.core.controller.admin.truck.vo.OrderDataSaveVO;
import com.xgk.boot.module.core.controller.admin.truck.vo.TruckOrderVO;
import com.xgk.boot.module.core.dal.dto.TruckOrderDto;
import com.xgk.boot.module.core.logistics.service.TruckOrderCommonService;
import com.xgk.boot.module.core.logistics.service.mothership.dto.OrderQuotationDto;
import com.xgk.boot.module.core.logistics.service.mothership.response.RateDto;
import com.xgk.boot.module.core.service.truck.TruckOrderQuotationServiceImpl;
import com.xgk.boot.module.infra.idempotent.annotate.RequestLock;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Tag(name = "管理后台 - 卡车订单询价")
@RestController
@RequestMapping("/system/truck-order-quotation")
public class OrderQuotationController {

    @Resource
    private TruckOrderQuotationServiceImpl truckOrderQuotationService;
    @Resource
    private TruckOrderCommonService truckOrderCommonService;

    @PostMapping("/quotation")
    @Operation(summary = "订单询价")
    public CommonResult<List<RateDto>> quotation(@Valid @RequestBody OrderDataSaveVO saveData) {

        TruckOrderDto dto = truckOrderQuotationService.prepareOrderDto(saveData);
        List<RateDto> logisticsQuotationList
                = truckOrderCommonService.getLogisticsQuotationList(dto);
        if(logisticsQuotationList == null || logisticsQuotationList.isEmpty() ) {
            logisticsQuotationList =new ArrayList<>();
        }

        return CommonResult.success(logisticsQuotationList);
    }

    //    @RequestLock
    @PostMapping("/save-order")
    @Operation(summary = "创建订单")
    public CommonResult<Object> saveOrder(@Valid @RequestBody OrderDataSaveVO saveData) {
        TruckOrderDto dto = truckOrderQuotationService.prepareOrderDto(saveData);
        //检测所选报价是否有表单填写不合规的地方
        OrderQuotationDto quote = truckOrderQuotationService.getQuote(dto.getTruckOrdersDO(),saveData);
        //下单保存前置检测
        truckOrderQuotationService.preOrderCheck(quote);

        //检测通过，保存订单信息
        TruckOrderDto truckOrderDto = truckOrderQuotationService.saveOrder(dto);

        //真实触发下单
        Boolean success =truckOrderCommonService.createOrder(dto,quote);
        if(success) {
            return CommonResult.success(truckOrderDto);
        }else{
            return CommonResult.error(-1,"创建订单失败");
        }
    }
}
